package com.itheima.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendVideoTask {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Scheduled(cron = "0 0/1 * * * ?")
    //@Scheduled(cron = "0 * 0/1 * * ?")
    public void recommendVideo() {
        System.out.println("开始视频推荐");
        Set<String> keys = stringRedisTemplate.keys("QUANZI_VIDEO_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)){
            for (String key : keys) {
                 key = key.replace("QUANZI_VIDEO_RECOMMEND_", "");
                Query query=new Query(
                        Criteria.where("userId").is(Long.valueOf(key))
                );
                 mongoTemplate.remove(query, RecommendVideo.class);
                String videoValue = stringRedisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_"+key);
                String[] vidArray = videoValue.split(",");
                for (String vid : vidArray) {
                    RecommendVideo recommendVideo=new RecommendVideo();
                    recommendVideo.setDate(System.currentTimeMillis());
                    recommendVideo.setScore(RandomUtil.randomDouble(70,90));
                    recommendVideo.setVid(Long.valueOf(vid));
                    recommendVideo.setUserId(Long.valueOf(key));
                    Query query1=new Query(
                            Criteria.where("vid").is(Long.valueOf(vid))
                    );
                    Video video = mongoTemplate.findOne(query1, Video.class);
                    recommendVideo.setVideoId(video.getId());
                    mongoTemplate.save(recommendVideo);
                }
                stringRedisTemplate.delete("QUANZI_VIDEO_RECOMMEND_"+key);
            }
        }

    }
}
